<?php

namespace App\Kuafu\Wechat\Controller\Applet;

use App\Kuafu\Customer\Service\CustomerPlatformService;
use App\Kuafu\Order\Enum\CodeEnum;
use App\Kuafu\Order\Service\OrderService;
use App\Kuafu\Shop\Enum\ShopCodeEnum;
use App\Kuafu\Shop\Service\ShopService;
use App\Kuafu\User\Service\AuthService;
use App\Kuafu\Wechat\Service\WechatSendMessageService;
use App\Kuafu\Wechat\Service\WechatService;
use Illuminate\Http\Request;
use App\Kuafu\Base\Controller\BaseController;

class WechatController extends BaseController
{
    /**
     * 支付订单发送消息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Kuafu\Wechat\Exceptions\WechatException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function payOrderSendMessage(Request $request)
    {
        $platformId = $request->header('platformId');
        $orderId    = (int)$request->orderId;
        $userId     = CustomerPlatformService::getUserId($request);
        $field      = ['shopId', 'orderId', 'serialNum', 'createdAt'];
        $orderInfo  = OrderService::getUserOrderFieldByOrderId($userId, $orderId, $field, $this->shopId);
        $shopInfo   = ShopService::getShopInfo($orderInfo['shopId']);
        if ($orderInfo) {
            $userOpenId          = CustomerPlatformService::getUserFieldByUserId($userId, $platformId, ['openid']);
            $openid              = $userOpenId['openid'];
            $shopName            = $shopInfo['name'];
            $address             = $shopInfo['address'];
            $serialNum           = $orderInfo['serialNum'];
            $orderCreatedTime    = $orderInfo['createdAt'];
            $payOrderSendMessage = WechatSendMessageService::PayOrderSendMessage($openid, $shopName, $serialNum,
                $orderId, $orderCreatedTime, $address, $shopInfo['id']);
            return $this->success($payOrderSendMessage);
        }
    }

    /**
     * 获取模版列表
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Kuafu\Wechat\Exceptions\WechatException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function getTemplateList(Request $request)
    {
        $type         = (int)$request->get('type');
        $shopId       = $this->shopId;
        $templateList = WechatService::getTemplateList($type, $shopId);
        return $this->success($templateList);
    }


    public function createAppletQrCode(Request $request)
    {
        $shopId = $this->shopId;
        $path   = config('wechat.indexPagePath');
        if ($shopId) {
            $path = config('wechat.indexPagePath') . "?shopId=$shopId";
        }
        $data   = array("path" => $path, "width" => 150);
        $qrCode = WechatService::createQrCode(CodeEnum::QR_CODE_TWO, $data, $shopId);
        return $this->success(['image' => $qrCode]);
    }
}

